package com.ttdj.cmel.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.ttdj.cmel.service.CMELUpdataIntentService;
import com.ttdj.cmel.utils.HmSharedPreferencesUtils;

import java.io.File;

/**
 * Created by gaopeng on 2018/7/11.
 */

public class UpdateAppReceiver extends BroadcastReceiver {
    public static final String TAG = "UpdateAppReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "UpdateAppReceiver intent：：" + intent.getAction());
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
            try {
                DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                DownloadManager.Query query = new DownloadManager.Query();
                //在广播中取出下载任务的id
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0L);
                long launcherId = (long) HmSharedPreferencesUtils.getParam("showboomApkID", -1L);
                Log.e(TAG, "launcherId ：：" + launcherId + "；广播ID：：" + id);
                if (launcherId != id) return;
                query.setFilterById(id);
                Cursor c = manager.query(query);
                String filename = "";
                if (c.moveToFirst()) {
                    String fileUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                        if (fileUri != null) {
                            /*filename = Uri.parse(fileUri).getPath();
                            File apkfile = new File(filename);
                            Intent mIntent = new Intent(context, CMELUpdataIntentService.class);
                            mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri contentUri = FileProvider.getUriForFile(context,
                                    "com.showboom.usercenter.fileprovider",
                                    apkfile);
                            intent.putExtra("pull_apk_type", 2);
                            mIntent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                            context.startActivity(mIntent);*/
                            CMELUpdataIntentService.startService(context, 2);
                        }
                    } else {
                        //获取文件下载路径
                        filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                        Log.e(TAG, "下载文件路径=" + filename);
                        boolean mSupportSilentInstall = Build.BRAND.equals("showboom");
                        if (mSupportSilentInstall && filename != null) {
                            Intent upIntent = new Intent("com.heimilink.action.install_or_delete");
                            upIntent.putExtra("event", "install");
                            upIntent.putExtra("pkgName", context.getPackageName());
                            upIntent.putExtra("path", filename);
                            context.sendBroadcast(upIntent);
                            Log.e(TAG, "静默安装 包名=" + context.getPackageName() + "；安装文件路径：：" + filename);
                        } else {
                            File apkfile = new File(filename);
                            Intent mIntent = new Intent(Intent.ACTION_VIEW);
                            mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mIntent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
                            context.startActivity(mIntent);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (intent.getAction().equals("com.heimilink.installed_action")) {
            String packageName = intent.getStringExtra("install_name");
//            Log.e(App.TAG, "静默安装：：" + packageName + "：：本应用=" + context.getPackageName());
            if (packageName.equals(context.getPackageName())) {
                Log.e(TAG, "安装成功");
//                Intent mIntent = new Intent(Intent.ACTION_MAIN);
//                mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                mIntent.addCategory(Intent.CATEGORY_HOME);
//                context.startActivity(mIntent);
            }
        }
    }
}
